package cn.edu.servlet;

import cn.edu.entity.City;
import cn.edu.entity.Province;
import cn.edu.service.CityService;
import cn.edu.service.ProvinceService;
import cn.edu.service.impl.CityServiceImpl;
import cn.edu.service.impl.ProvinceServiceImpl;
import cn.edu.util.URIUtil;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 *  1.创建了tb_province的实体类 Province
 *  2.创建Dao层            IProvince
 *  3.创建Dao的实现层      IprovinceImpl
 *  4.创建service层        ProvinceService
 *  5.创建service的实现层  ProvinceServiceImpl
 *
 *  6.  在ProvinceServiceImpl里面实现dao层的调用.也就是创建dao层的变量
 *
 *  7. 在Servlet中实现服务层的调用 ,也就是创建 service层的变量
 * */


@WebServlet("*.jquery")
public class City3Servlet extends HttpServlet {

    ProvinceService provinceService;
    CityService cityService;


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = URIUtil.subUri(req.getRequestURI());
        if("province".equals(path)){
            //获取所有的省份并将数据返回到city.jsp页面
            provinceService = new ProvinceServiceImpl();
            List<Province> list = provinceService.getProvinces();
            req.setAttribute("list",list);
            req.getRequestDispatcher("/front/city3.0.jsp").forward(req,resp);
        }else if("city".equals(path)){
            //获取所有匹配的省份id的市级单位
            //1.测试是否能从页面拿到省份ID
            System.out.println(req.getParameter("u_id"));
            String idStr  = req.getParameter("u_id");
            //2.从数据库中去获取对应的市级单位
            cityService = new CityServiceImpl();
            List<City> cities = cityService.getAlllist(Integer.valueOf(idStr));

            String listStr = JSON.toJSONString(cities);
            resp.setContentType("txt/html;charset=utf-8");
            resp.getWriter().write(listStr);
        }

    }
}
